package com.superyee.commonlib.utils.gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.superyee.commonlib.utils.AppLog;

import java.lang.reflect.Type;
import java.util.ArrayList;

/**
 * Created by guoguo on 2017/11/24.
 */

public class GsonHelper {

    private static Gson mGson;

    static {
        mGson = new GsonBuilder()
                .registerTypeAdapter(Integer.class, new IntegerDefault0Adapter())
                .registerTypeAdapter(int.class, new IntegerDefault0Adapter())
                .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                .registerTypeAdapter(Long.class, new LongDefault0Adapter())
                .registerTypeAdapter(long.class, new LongDefault0Adapter())
                .create();
    }

    public static <T> T fromJson(String json, Type typeOfT) {
        try {
            T target = mGson.fromJson(json, typeOfT);
            return target;
        } catch (Exception e) {
            e.printStackTrace();
            AppLog.printE("GsonHelper", e.getMessage() + " " + json);
        }
        return null;
    }

    public static <T> ArrayList<T> fromJsonToList(String json, Class<T> cls) {
        Type type = new TypeToken<ArrayList<JsonObject>>() {
        }.getType();
        ArrayList<JsonObject> jsonObjs = new Gson().fromJson(json, type);

        ArrayList<T> listOfT = new ArrayList<T>();
        if (jsonObjs != null) {
            for (JsonObject jsonObj : jsonObjs) {
                listOfT.add(fromJson(jsonObj, cls));
            }
        }
        return listOfT;
    }

    public static <T> T fromJson(JsonObject json, Class<T> classOfT) {
        try {
            return mGson.fromJson(json, classOfT);
        } catch (Exception e) {
        }
        return null;
    }

    public static <T> T fromJson(String json, Class<T> classOfT) {
        try {
            return mGson.fromJson(json, classOfT);
        } catch (Exception e) {
        }
        return null;
    }

    public static String getValue(String json, String name) {
        JSONObject jsonObject = JSON.parseObject(json);
        if (jsonObject != null) {
            return jsonObject.getString(name);
        }
        return null;
    }

}
